package com.sky.service.impl;

import com.sky.dto.AuditMerchantDTO;
import com.sky.dto.MerchantPageQueryDTO;
import com.sky.dto.MerchantUpdateDTO;
import com.sky.entity.Merchant;
import com.sky.entity.MerchantCategory;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.MerchantCategoryMapper;
import com.sky.service.AdminMerchantService;
import com.sky.service.MerchantService;
import com.sky.vo.MerchantStatusCount;
import com.sky.vo.MerchantVO;
import com.sky.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Collectors;

/**
 * 商家管理服务实现类
 */
@Service
public class AdminMerchantServiceImpl implements AdminMerchantService {
    private static final Logger log = LoggerFactory.getLogger(AdminMerchantServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;
    
    @Autowired
    private MerchantCategoryMapper merchantCategoryMapper;

    @Override
    public PageResult<MerchantVO> getPendingMerchants(MerchantPageQueryDTO merchantPageQueryDTO) {
        // 计算分页参数
        int page = merchantPageQueryDTO.getPage();
        int pageSize = merchantPageQueryDTO.getPageSize();
        int start = (page - 1) * pageSize;
        merchantPageQueryDTO.setStart(start);
        
        // 使用关联查询获取带有分类信息的商家列表
        List<MerchantVO> merchantVOs = merchantMapper.selectMerchantWithCategory(merchantPageQueryDTO);
        Integer total = merchantMapper.selectCount(merchantPageQueryDTO);
        
        return new PageResult<>((long)total, merchantVOs);
    }

    @Override
    public void auditMerchant(String action, AuditMerchantDTO auditMerchantDTO) {
        // 直接更新状态，避免更新其他可能导致问题的字段
        MerchantUpdateDTO statusUpdateDTO = new MerchantUpdateDTO();
        statusUpdateDTO.setId(auditMerchantDTO.getId());
        statusUpdateDTO.setUpdatedAt(LocalDateTime.now());
        
        if ("approve".equals(action)) {
            statusUpdateDTO.setStatus("active");
            merchantMapper.updateStatus(statusUpdateDTO);
        } else if ("reject".equals(action)) {
            // 使用inactive状态而不是rejected，与前端状态系统保持一致
            statusUpdateDTO.setStatus("inactive");
            merchantMapper.updateStatus(statusUpdateDTO);
        }
    }

    @Override
    public PageResult<MerchantVO> getAllMerchants(MerchantPageQueryDTO merchantPageQueryDTO) {
        // 计算分页参数
        int page = merchantPageQueryDTO.getPage();
        int pageSize = merchantPageQueryDTO.getPageSize();
        int start = (page - 1) * pageSize;
        merchantPageQueryDTO.setStart(start);
        
        // 使用关联查询获取带有分类信息的商家列表
        List<MerchantVO> merchantVOs = merchantMapper.selectMerchantWithCategory(merchantPageQueryDTO);
        Integer total = merchantMapper.selectCount(merchantPageQueryDTO);
        
        return new PageResult<>((long)total, merchantVOs);
    }
    
    @Override
    public void changeStatus(Long id, Boolean status) {
        // 将布尔状态值转换为数据库支持的值
        String statusStr = status ? "active" : "inactive";
        MerchantUpdateDTO statusUpdateDTO = new MerchantUpdateDTO();
        statusUpdateDTO.setId(id);
        statusUpdateDTO.setStatus(statusStr);
        statusUpdateDTO.setUpdatedAt(LocalDateTime.now());
        merchantMapper.updateStatus(statusUpdateDTO);
    }

    @Override
    public void reauditMerchant(Long id) {
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant != null && "inactive".equals(merchant.getStatus())) {
            // 直接更新状态，避免更新其他可能导致问题的字段
            MerchantUpdateDTO statusUpdateDTO = new MerchantUpdateDTO();
            statusUpdateDTO.setId(id);
            statusUpdateDTO.setStatus("pending");
            statusUpdateDTO.setUpdatedAt(LocalDateTime.now());
            merchantMapper.updateStatus(statusUpdateDTO);
        }
    }

    @Override
    public MerchantVO getMerchantDetail(Long id) {
        // 查询商家基础信息
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant != null) {
            // 转换为VO对象
            MerchantVO merchantVO = convertToVO(merchant);
            
            // 如果有分类ID，查询分类名称
            if (merchant.getCategoryId() != null) {
                MerchantCategory category = merchantCategoryMapper.selectById(merchant.getCategoryId().intValue());
                if (category != null) {
                    merchantVO.setCategoryName(category.getName());
                } else {
                    merchantVO.setCategoryName("未分类");
                }
            } else {
                merchantVO.setCategoryName("未分类");
            }
            
            return merchantVO;
        }
        
        return null;
    }

    @Override
    public MerchantStatusCount getMerchantStatusCount() {
        MerchantStatusCount count = new MerchantStatusCount();
        
        // 创建查询DTO
        MerchantPageQueryDTO queryDTO = new MerchantPageQueryDTO();
        
        // 统计待审核商家数量
        queryDTO.setStatus("pending");
        count.setPending(merchantMapper.selectCount(queryDTO));
        
        // 统计正常商家数量
        queryDTO.setStatus("active");
        count.setActive(merchantMapper.selectCount(queryDTO));
        
        // 统计禁用商家数量
        queryDTO.setStatus("inactive");
        count.setInactive(merchantMapper.selectCount(queryDTO));
        
        return count;
    }

    /**
     * 将实体类转换为VO
     */
    private MerchantVO convertToVO(Merchant merchant) {
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        // 注意：数据库中可能没有apply_time字段，这里根据需要调整
        merchantVO.setApplyTime(merchant.getCreatedAt());
        // 确保description字段正确映射
        merchantVO.setDescription(merchant.getDescription());
        return merchantVO;
    }
    
    @Override
    public void updateBusinessStatus(Long id, String businessStatus) {
        // 调用Mapper更新商家营业状态
        merchantMapper.updateBusinessStatus(id, businessStatus);
        // 更新修改时间
        Merchant merchant = new Merchant();
        merchant.setId(id);
        merchant.setUpdatedAt(LocalDateTime.now());
        merchantMapper.update(merchant);
    }
    
    @Override
    public List<MerchantCategory> getAllMerchantCategories() {
        log.info("查询所有商家分类");
        return merchantMapper.selectAllCategories();
    }
    
    @Override
    public MerchantCategory getMerchantCategoryById(Long id) {
        log.info("根据ID查询商家分类: {}", id);
        return merchantCategoryMapper.selectById(id.intValue());
    }
}